<template>
  <div class="websocket-monitor" :style="{ '--local-mount-height': cssVar ? `var(${cssVar})` : '100%' }">
    <div class="header">
      <div class="controls">
        <div class="broadcast-control">
          <input v-model="broadcastMessage" :placeholder="$t('message.socket.broadcastMessage')" />
          <button @click="handleBroadcast">{{ $t('message.socket.broadcast') }}</button>
        </div>
        <div class="status-indicator">
          <div :class="['status-dot', socketStore.isServerActive ? 'active' : 'inactive']"></div>
          <span>WebSocket: {{ socketStore.serverStatusText }}</span>
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="dashboard">
      <el-col :span="8" class="connections-panel">
        <h2>{{ $t('message.socket.activeConnections')+':'+ socketStore.activeConnectionCount }}</h2>
        <div class="connections-list">
          <div
            v-for="conn in socketStore.activeConnections"
            :key="conn.clientId"
            class="connection-item"
            :class="{ active: conn.connected }"
          >
            <div class="connection-header">
              <span class="client-id">{{ conn.clientId }}</span>
              <span class="ip">{{ conn.ip }}</span>
              <span class="status">{{ conn.connected ?  $t('message.socket.connected') : $t('message.socket.disconnected') }}</span>
            </div>
            <div class="connection-details">
              <div class="connection-time">
                {{ $t('message.socket.connectedAt') + formatTime(conn.timestamp) }}
              </div>
              <div class="connection-actions">
                <input
                  v-model="socketStore.clientMessages[conn.clientId]"
                  :placeholder="$t('message.socket.sendMessage')"
                  @keyup.enter="sendToClient(conn.clientId)"
                />
                <button
                  @click="sendToClient(conn.clientId)"
                  :disabled="!socketStore.clientMessages[conn.clientId]?.trim()"
                >
                  {{ $t('message.socket.send') }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="16" class="logs-panel">
        <h2>{{ $t('message.socket.eventLogs') }}</h2>
        <div class="logs-controls">
          <button @click="socketStore.clearLogs">{{ $t('message.socket.clearLogs') }}</button>
          <label>
            <input type="checkbox" v-model="autoScroll" /> {{ $t('message.socket.autoScroll') }}
          </label>
        </div>
        <div class="logs-list" ref="logsContainer">
          <div
            v-for="(log, index) in socketStore.eventLogs"
            :key="index"
            class="log-item"
            :class="log.type"
          >
            <span class="log-time">[{{ formatTime(log.timestamp) }}]</span>
            <span class="log-message">{{ log.message }}</span>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts" name="SocketPanel">
import { ref, onMounted, nextTick, getCurrentInstance } from 'vue'
import { useWebSocketStore } from '@renderer/stores/websocketStore'

const instance = getCurrentInstance();
const cssVar = instance?.appContext.config.globalProperties.$cssVarName;
const socketStore = useWebSocketStore()

// 组件内部状态
const broadcastMessage = ref('')
const autoScroll = ref(true)
const logsContainer = ref<HTMLDivElement | null>(null)

// 方法
const formatTime = (timestamp: string) => {
  return new Date(timestamp).toLocaleTimeString()
}

const handleBroadcast = async () => {
  if (broadcastMessage.value.trim()) {
    await socketStore.broadcastMessage(broadcastMessage.value)
    broadcastMessage.value = ''
  }
}

const sendToClient = async (clientId: string) => {
  const message = socketStore.clientMessages[clientId]?.trim()
  if (message) {
    const success = await socketStore.sendToClient(clientId, message)
    if (success) {
      socketStore.clientMessages[clientId] = ''
    }
  }
}

const scrollToBottom = () => {
  if (autoScroll.value && logsContainer.value) {
    logsContainer.value.scrollTop = logsContainer.value.scrollHeight
  }
}

// 组件挂载时
onMounted(() => {
  // 同步客户端列表
  socketStore.syncClientList();

  // 确保所有客户端都有初始化的消息字段
  socketStore.activeConnections.forEach(conn => {
    if (socketStore.clientMessages[conn.clientId] === undefined) {
      socketStore.clientMessages[conn.clientId] = ''
    }
  })

  // 监听新客户端连接，自动初始化消息字段
  socketStore.$subscribe((mutation) => {
    if (mutation.storeId === 'websocket' && mutation.payload) {
      if ('activeConnections' in mutation.payload) {
        socketStore.activeConnections.forEach(conn => {
          if (socketStore.clientMessages[conn.clientId] === undefined) {
            socketStore.clientMessages[conn.clientId] = ''
          }
        })
      }

      // 日志滚动逻辑
      if ('eventLogs' in mutation.payload) {
        nextTick(scrollToBottom)
      }
    }
  })

  // 初始滚动到底部
  nextTick(scrollToBottom)
})
</script>

<style scoped>
.websocket-monitor {
  display: flex;
  flex-direction: column;
  height: calc(var(--local-mount-height) - 85px);
  padding: 20px;
  background-color: #1e1e2e;
  color: #cdd6f4;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

.header {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #313244;
}

.header h1 {
  margin: 0 0 15px 0;
  color: #cba6f7;
}

.controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.broadcast-control {
  display: flex;
  gap: 10px;
}

.broadcast-control input {
  flex: 1;
  padding: 10px;
  border: 1px solid #45475a;
  border-radius: 4px;
  background-color: #11111b;
  color: #cdd6f4;
  min-width: 300px;
}

.broadcast-control button,
.connection-actions button {
  padding: 10px 15px;
  background-color: #a6e3a1;
  color: #1e1e2e;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.broadcast-control button:hover {
  background-color: #94e2d5;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-dot.active {
  background-color: #a6e3a1;
  box-shadow: 0 0 8px rgba(166, 227, 161, 0.5);
}

.status-dot.inactive {
  background-color: #f38ba8;
}

.dashboard {
  height: 100%;
}

.connections-panel, .logs-panel {
  background-color: #11111b;
  border-radius: 8px;
  border: 1px solid #313244;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.connections-panel h2, .logs-panel h2 {
  margin: 0;
  padding: 15px 20px;
  background-color: #181825;
  border-bottom: 1px solid #313244;
  color: #89b4fa;
}

.connections-list, .logs-list {
  flex: 1;
  overflow-y: auto;
  padding: 15px;
}

.connection-item {
  padding: 15px;
  margin-bottom: 12px;
  border-radius: 6px;
  background-color: #181825;
  border-left: 4px solid #a6e3a1;
  transition: all 0.3s ease;
}

.connection-item:not(.active) {
  border-left-color: #f38ba8;
  opacity: 0.7;
}

.connection-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 0.95em;
}

.client-id {
  font-weight: bold;
  color: #f5c2e7;
  font-family: monospace;
}

.ip {
  color: #89b4fa;
}

.status {
  font-weight: bold;
  color: #a6e3a1;
}

.connection-item:not(.active) .status {
  color: #f38ba8;
}

.connection-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.connection-time {
  font-size: 0.85em;
  color: #a6adc8;
}

.connection-actions {
  display: flex;
  gap: 8px;
}

.connection-actions input {
  flex: 1;
  padding: 8px;
  border: 1px solid #45475a;
  border-radius: 4px;
  background-color: #1e1e2e;
  color: #cdd6f4;
}

.connection-actions button {
  padding: 8px 12px;
  background-color: #89b4fa;
}

.connection-actions button:hover {
  background-color: #74c7ec;
}

.connection-actions button:disabled {
  background-color: #6c7086;
  cursor: not-allowed;
  opacity: 0.7;
}

.logs-controls {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  padding: 10px 15px;
  background-color: #181825;
  border-bottom: 1px solid #313244;
}

.logs-controls button {
  padding: 6px 12px;
  background-color: #f5e0dc;
  color: #1e1e2e;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.logs-controls button:hover {
  background-color: #f2cdcd;
}

.logs-controls label {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.9em;
}

.log-item {
  padding: 10px;
  margin-bottom: 8px;
  border-radius: 4px;
  font-size: 0.9em;
  font-family: monospace;
}

.log-time {
  color: #a6adc8;
  margin-right: 10px;
}

.connection {
  background-color: rgba(166, 227, 161, 0.1);
}

.disconnection {
  background-color: rgba(243, 139, 168, 0.1);
}

.message {
  background-color: rgba(137, 180, 250, 0.1);
}

.info {
  background-color: rgba(180, 190, 254, 0.1);
}

.error {
  background-color: rgba(243, 139, 168, 0.2);
}
</style>
